// 俄罗斯方块核心逻辑
class Tetris {
    constructor() {
        // 游戏常量
        this.COLUMNS = 10;
        this.ROWS = 20;
        this.BLOCK_SIZE = 30;
        
        // 游戏状态
        this.board = Array(this.ROWS).fill().map(() => Array(this.COLUMNS).fill(0));
        this.currentPiece = null;
        this.nextPiece = null;
        this.gameOver = false;
        this.paused = false;
        this.score = 0;
        this.lines = 0;
        this.level = 1;
        this.dropInterval = 1000; // 初始下落速度（毫秒）
        this.lastTime = 0;
        this.dropCounter = 0;
        
        // 方块颜色
        this.colors = [
            null,
            '#FF5252', // I
            '#536DFE', // J
            '#FFC107', // L
            '#4CAF50', // O
            '#E91E63', // S
            '#FF9800', // T
            '#2196F3'  // Z
        ];
        
        // 方块形状定义
        this.tetrominos = {
            0: [],
            1: [  // I
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [0, 0, 0, 0],
                [0, 0, 0, 0]
            ],
            2: [  // J
                [2, 0, 0],
                [2, 2, 2],
                [0, 0, 0]
            ],
            3: [  // L
                [0, 0, 3],
                [3, 3, 3],
                [0, 0, 0]
            ],
            4: [  // O
                [4, 4],
                [4, 4]
            ],
            5: [  // S
                [0, 5, 5],
                [5, 5, 0],
                [0, 0, 0]
            ],
            6: [  // T
                [0, 6, 0],
                [6, 6, 6],
                [0, 0, 0]
            ],
            7: [  // Z
                [7, 7, 0],
                [0, 7, 7],
                [0, 0, 0]
            ]
        };
        
        // 初始化游戏
        this.reset();
    }
    
    // 重置游戏
    reset() {
        this.board = Array(this.ROWS).fill().map(() => Array(this.COLUMNS).fill(0));
        this.gameOver = false;
        this.paused = false;
        this.score = 0;
        this.lines = 0;
        this.level = 1;
        this.dropInterval = 1000;
        this.currentPiece = this.createPiece();
        this.nextPiece = this.createPiece();
    }
    
    // 创建新方块
    createPiece() {
        const type = Math.floor(Math.random() * 7) + 1; // 1-7
        const piece = {
            type: type,
            shape: this.tetrominos[type],
            x: Math.floor(this.COLUMNS / 2) - Math.floor(this.tetrominos[type][0].length / 2),
            y: 0
        };
        return piece;
    }
    
    // 旋转方块
    rotate(piece) {
        const rotated = [];
        const size = piece.shape.length;
        
        // 初始化旋转后的数组
        for (let i = 0; i < size; i++) {
            rotated[i] = Array(size).fill(0);
        }
        
        // 执行旋转
        for (let y = 0; y < size; y++) {
            for (let x = 0; x < size; x++) {
                rotated[x][size - 1 - y] = piece.shape[y][x];
            }
        }
        
        return rotated;
    }
    
    // 检查移动是否有效
    isValidMove(piece, moveX, moveY, newShape = null) {
        const shape = newShape || piece.shape;
        
        for (let y = 0; y < shape.length; y++) {
            for (let x = 0; x < shape[y].length; x++) {
                if (shape[y][x] !== 0) {
                    const newX = piece.x + x + moveX;
                    const newY = piece.y + y + moveY;
                    
                    // 检查边界
                    if (newX < 0 || newX >= this.COLUMNS || newY >= this.ROWS) {
                        return false;
                    }
                    
                    // 检查是否与已落下的方块碰撞
                    if (newY >= 0 && this.board[newY][newX] !== 0) {
                        return false;
                    }
                }
            }
        }
        
        return true;
    }
    
    // 移动方块
    move(deltaX) {
        if (!this.paused && !this.gameOver && this.isValidMove(this.currentPiece, deltaX, 0)) {
            this.currentPiece.x += deltaX;
            return true;
        }
        return false;
    }
    
    // 下移方块
    drop() {
        if (!this.paused && !this.gameOver) {
            if (this.isValidMove(this.currentPiece, 0, 1)) {
                this.currentPiece.y += 1;
                return true;
            } else {
                this.lockPiece();
                return false;
            }
        }
        return false;
    }
    
    // 硬下落（直接落到底部）
    hardDrop() {
        if (!this.paused && !this.gameOver) {
            while (this.drop()) {}
            this.lockPiece();
        }
    }
    
    // 旋转当前方块
    rotateCurrent() {
        if (!this.paused && !this.gameOver) {
            const rotatedShape = this.rotate(this.currentPiece);
            
            // 尝试直接旋转
            if (this.isValidMove(this.currentPiece, 0, 0, rotatedShape)) {
                this.currentPiece.shape = rotatedShape;
                return true;
            }
            
            // 尝试墙壁踢腿（wall kick）
            // 先尝试左移一格旋转
            if (this.isValidMove(this.currentPiece, -1, 0, rotatedShape)) {
                this.currentPiece.x -= 1;
                this.currentPiece.shape = rotatedShape;
                return true;
            }
            
            // 尝试右移一格旋转
            if (this.isValidMove(this.currentPiece, 1, 0, rotatedShape)) {
                this.currentPiece.x += 1;
                this.currentPiece.shape = rotatedShape;
                return true;
            }
            
            // 尝试下移一格旋转
            if (this.isValidMove(this.currentPiece, 0, 1, rotatedShape)) {
                this.currentPiece.y += 1;
                this.currentPiece.shape = rotatedShape;
                return true;
            }
        }
        return false;
    }
    
    // 锁定当前方块到游戏板上
    lockPiece() {
        const { shape, x, y, type } = this.currentPiece;
        
        // 将方块添加到游戏板
        for (let py = 0; py < shape.length; py++) {
            for (let px = 0; px < shape[py].length; px++) {
                if (shape[py][px] !== 0) {
                    const boardY = y + py;
                    if (boardY >= 0) {
                        this.board[boardY][x + px] = type;
                    }
                }
            }
        }
        
        // 检查并消除完整的行
        this.clearLines();
        
        // 生成新方块
        this.currentPiece = this.nextPiece;
        this.nextPiece = this.createPiece();
        
        // 检查游戏是否结束
        if (!this.isValidMove(this.currentPiece, 0, 0)) {
            this.gameOver = true;
        }
    }
    
    // 消除完整的行
    clearLines() {
        let linesCleared = 0;
        
        for (let y = this.ROWS - 1; y >= 0; y--) {
            let isLineComplete = true;
            
            for (let x = 0; x < this.COLUMNS; x++) {
                if (this.board[y][x] === 0) {
                    isLineComplete = false;
                    break;
                }
            }
            
            if (isLineComplete) {
                // 移除完整的行
                this.board.splice(y, 1);
                // 在顶部添加空行
                this.board.unshift(Array(this.COLUMNS).fill(0));
                // 重新检查当前行（因为上面的行下移了）
                y++;
                linesCleared++;
            }
        }
        
        // 更新分数和行数
        if (linesCleared > 0) {
            this.updateScore(linesCleared);
        }
    }
    
    // 更新分数
    updateScore(linesCleared) {
        // 根据消除的行数计算分数
        const linePoints = [0, 100, 300, 500, 800]; // 0, 1, 2, 3, 4行的分数
        this.score += linePoints[linesCleared] * this.level;
        this.lines += linesCleared;
        
        // 根据消除的行数更新等级
        const newLevel = Math.floor(this.lines / 10) + 1;
        if (newLevel > this.level) {
            this.level = newLevel;
            // 随着等级提升，下落速度加快
            this.dropInterval = Math.max(100, 1000 - (this.level - 1) * 100);
        }
    }
    
    // 暂停/继续游戏
    togglePause() {
        if (!this.gameOver) {
            this.paused = !this.paused;
            return this.paused;
        }
        return false;
    }
    
    // 更新游戏状态
    update(time = 0) {
        if (!this.paused && !this.gameOver) {
            const deltaTime = time - this.lastTime;
            this.lastTime = time;
            
            this.dropCounter += deltaTime;
            if (this.dropCounter > this.dropInterval) {
                this.drop();
                this.dropCounter = 0;
            }
        }
    }
    
    // 获取游戏状态
    getState() {
        return {
            board: this.board,
            currentPiece: this.currentPiece,
            nextPiece: this.nextPiece,
            score: this.score,
            lines: this.lines,
            level: this.level,
            gameOver: this.gameOver,
            paused: this.paused,
            colors: this.colors,
            BLOCK_SIZE: this.BLOCK_SIZE,
            COLUMNS: this.COLUMNS,
            ROWS: this.ROWS
        };
    }
}